package controllers

import (
	"net/http"
	
	"github.com/gin-gonic/gin"
	"myblog/services"
	"myblog/utils"
)

type ArticleController struct {
	service *services.ArticleService
}

func NewArticleController(service *services.ArticleService) *ArticleController {
	return &ArticleController{service: service}
}

func (c *ArticleController) HomePage(ctx *gin.Context) {
	articles, err := c.service.GetAllArticles()
	if err != nil {
		ctx.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": "获取文章列表失败",
		})
		return
	}
	
	ctx.HTML(http.StatusOK, "index.html", gin.H{
		"articles": articles,
	})
}

func (c *ArticleController) ArticleDetail(ctx *gin.Context) {
	slug := ctx.Param("slug")
	article, err := c.service.GetArticleBySlug(slug)
	if err != nil {
		ctx.HTML(http.StatusNotFound, "error.html", gin.H{
			"error": "文章不存在",
		})
		return
	}
	
	htmlContent := utils.RenderMarkdown(article.Content)
	
	ctx.HTML(http.StatusOK, "article/detail.html", gin.H{
		"article": article,
		"content": htmlContent, // 这里传递的是字符串，safeHTML会处理
	})
}